package com.diamond.web.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.diamond.core.entity.APIResult;
import com.diamond.core.util.ServerUtils;

public class ApiInterceptor implements HandlerInterceptor{
	Logger log = Logger.getLogger(getClass());
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//不拦截jsonp请求
		if(request.getRequestURI().matches(".*/jsonp/.*")){
			log.info("request jsonp api "+request.getRequestURI());
			return true;
		}
		
		//其它API请求，验证请求签名
		boolean isSign = ServerUtils.isSign(request);
		if(isSign){
			return true;
		}
		APIResult result = new APIResult();
		result.setSuccess(false);
		result.setStatusCode(APIResult.VALID_FAIL);
		result.setMessage("valid sign fail");
		ObjectMapper m = new ObjectMapper();
		response.getWriter().write(m.writeValueAsString(result));
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
